package xyz.wadewhy.basicstest.designPatterns.PrototypeModel;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.UUID;

/**
 * @ClassName PushMsg
 * @Description 业务用途
 * @Author zhongzihao
 * @Date 2021/12/24 4:08 下午
 * @Version 1.0
 **/
@Data
@AllArgsConstructor
@NoArgsConstructor
abstract class AbstractPushMsg implements Cloneable {
    private String name;
    private String resourceId;
    private String toUserId;

    @Override
    public AbstractPushMsg clone() {
        try {
            return (AbstractPushMsg) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new AssertionError();
        }
    }
}

class PushMsg extends AbstractPushMsg {
    public PushMsg(String name, String resourceId, String toUserId) {
        super(name, resourceId, toUserId);
    }
}

class TestDemo {
    private static final int NUM = 10;
    public static void main(String[] args) {
        //模拟推送，当一个商品上架，推送到用户中，只有toUserId不一致
        String resourceId = UUID.randomUUID().toString();
        String toUserId = UUID.randomUUID().toString();
        PushMsg msg = new PushMsg("iphone", resourceId, toUserId);
        System.err.println("原始消息：" + msg);
        for (int i = 0; i < NUM; i++) {
            PushMsg msg1 = (PushMsg) msg.clone();
            msg1.setToUserId(UUID.randomUUID().toString());
            System.out.println(msg1);
        }
    }

    /**
     * 每次都要实例化对象，利用原型模式就能解决，现在一般都用拷贝BeanUtils
     */
    public static void errorTest(){
        for (int i = 0; i < NUM; i++) {
            String resourceId = UUID.randomUUID().toString();
            PushMsg msg = new PushMsg("iphone", resourceId, UUID.randomUUID().toString());
            System.out.println(msg);
        }
    }
}